import express from 'express';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import db from '../config/db.js';
import { authenticate } from '../middleware/auth.js';

const router = express.Router();
const upload = multer({ dest: 'uploads/' });

// 验证是否是管理员
const isAdmin = async (req, res, next) => {
  try {
    // 由于登录时我们已经为admin用户设置了role='admin'，这里直接验证token中的role即可
    if (req.user && req.user.role === 'admin') {
      next();
    } else {
      return res.status(403).json({ message: '没有管理员权限' });
    }
  } catch (error) {
    console.error('管理员验证错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 管理员登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // 直接验证是否为默认管理员账号密码
    if (username === 'admin' && password === '123456') {
      // 生成JWT令牌
      const token = jwt.sign(
        { id: 1, username: 'admin', role: 'admin' },
        process.env.JWT_SECRET,
        { expiresIn: '24h' }
      );
      
      // 返回用户信息和令牌
      return res.json({
        token,
        user: {
          id: 1,
          username: 'admin',
          email: 'admin@example.com',
          avatar: '',
          role: 'admin'
        }
      });
    }
    
    // 如果不是默认账号，尝试从数据库验证（如果数据库表中有记录）
    const [rows] = await db.query(
      'SELECT id, username, password, email, avatar FROM users WHERE username = ?',
      [username]
    );
    
    if (rows.length === 0) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }
    
    const user = rows[0];
    const passwordMatch = await bcrypt.compare(password, user.password);
    
    if (!passwordMatch) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }
    
    // 生成JWT令牌
    const token = jwt.sign(
      { id: user.id, username: user.username, role: 'admin' },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );
    
    // 返回用户信息和令牌
    res.json({
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        avatar: user.avatar,
        role: 'admin'
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取管理员信息
router.get('/profile', authenticate, isAdmin, async (req, res) => {
  try {
    const [rows] = await db.query(
      'SELECT id, username, email, avatar, role FROM users WHERE id = ?',
      [req.user.id]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    res.json(rows[0]);
  } catch (error) {
    console.error('获取管理员信息错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取商品列表
router.get('/products', authenticate, isAdmin, async (req, res) => {
  try {
    const { page = 1, limit = 10, name, category, minPrice, maxPrice } = req.query;
    const offset = (page - 1) * limit;
    
    let query = 'SELECT * FROM products WHERE 1=1';
    const params = [];
    
    if (name) {
      query += ' AND name LIKE ?';
      params.push(`%${name}%`);
    }
    
    if (category) {
      query += ' AND category = ?';
      params.push(category);
    }
    
    if (minPrice) {
      query += ' AND price >= ?';
      params.push(minPrice);
    }
    
    if (maxPrice) {
      query += ' AND price <= ?';
      params.push(maxPrice);
    }
    
    const countQuery = query.replace('SELECT *', 'SELECT COUNT(*) as total');
    const [countRows] = await db.query(countQuery, params);
    const total = countRows[0].total;
    
    query += ' ORDER BY id DESC LIMIT ? OFFSET ?';
    params.push(Number(limit), Number(offset));
    
    const [rows] = await db.query(query, params);
    
    res.json({
      items: rows,
      total,
      page: Number(page),
      limit: Number(limit)
    });
  } catch (error) {
    console.error('获取商品列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取商品详情
router.get('/products/:id', authenticate, isAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    
    const [productRows] = await db.query(
      'SELECT * FROM products WHERE id = ?',
      [id]
    );
    
    if (productRows.length === 0) {
      return res.status(404).json({ message: '商品不存在' });
    }
    
    // 直接返回商品信息，不查询不存在的表
    const product = {
      ...productRows[0],
      price: parseFloat(productRows[0].price),
      gallery: [], // 提供空数组保持前端兼容性
      specifications: [] // 提供空数组保持前端兼容性
    };
    
    res.json(product);
  } catch (error) {
    console.error('获取商品详情错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 创建商品
router.post('/products', authenticate, isAdmin, async (req, res) => {
  try {
    const { name, category, price, stock, is_hot, description, image } = req.body;
    
    // 使用is_hot字段代替status
    const [result] = await db.query(
      'INSERT INTO products (name, description, price, category, stock, is_hot, image) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [name, description, price, category, stock, is_hot || 0, image]
    );
    
    const productId = result.insertId;
    
    res.status(201).json({ 
      id: productId,
      message: '商品创建成功'
    });
  } catch (error) {
    console.error('创建商品错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新商品
router.put('/products/:id', authenticate, isAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;
    
    // 构建动态更新SQL
    const keys = Object.keys(updateData);
    if (keys.length === 0) {
      return res.status(400).json({ message: '没有提供更新数据' });
    }
    
    const setClause = keys.map(key => `${key} = ?`).join(', ');
    const values = keys.map(key => updateData[key]);
    values.push(id);
    
    // 执行更新
    await db.query(
      `UPDATE products SET ${setClause} WHERE id = ?`,
      values
    );
    
    res.json({ message: '商品更新成功' });
  } catch (error) {
    console.error('更新商品错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除商品
router.delete('/products/:id', authenticate, isAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    
    // 直接删除产品，不需要处理不存在的表
    await db.query('DELETE FROM products WHERE id = ?', [id]);
    
    res.json({ message: '商品删除成功' });
  } catch (error) {
    console.error('删除商品错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 上传商品图片
router.post('/upload/product', authenticate, isAdmin, upload.single('file'), async (req, res) => {
  try {
    const file = req.file;
    if (!file) {
      return res.status(400).json({ message: '没有文件上传' });
    }
    
    console.log('接收到文件上传请求:', file);
    
    // 使用项目根目录下的uploads目录而不是server/uploads
    const uploadDir = path.join(process.cwd(), '../uploads/products');
    
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      console.log('创建上传目录:', uploadDir);
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    
    // 生成文件名
    const fileName = `${Date.now()}-${file.originalname}`;
    const filePath = path.join(uploadDir, fileName);
    
    console.log('文件将保存到:', filePath);
    
    // 移动文件
    fs.renameSync(file.path, filePath);
    
    // 返回文件URL (使用相对于网站根目录的路径)
    const fileUrl = `/uploads/products/${fileName}`;
    
    console.log('文件URL:', fileUrl);
    
    res.json({
      url: fileUrl,
      name: file.originalname
    });
  } catch (error) {
    console.error('上传图片错误:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取订单列表
router.get('/orders', authenticate, isAdmin, async (req, res) => {
  try {
    const { page = 1, limit = 10, orderId, user, status, startDate, endDate } = req.query;
    const offset = (page - 1) * limit;
    
    let query = `
      SELECT o.*, u.username as user, u.email
      FROM orders o
      JOIN users u ON o.user_id = u.id
      WHERE 1=1
    `;
    
    const params = [];
    
    if (orderId) {
      query += ' AND o.order_no LIKE ?';
      params.push(`%${orderId}%`);
    }
    
    if (user) {
      query += ' AND (u.username LIKE ? OR u.email LIKE ?)';
      params.push(`%${user}%`, `%${user}%`);
    }
    
    if (status) {
      query += ' AND o.status = ?';
      params.push(status);
    }
    
    if (startDate) {
      query += ' AND o.created_at >= ?';
      params.push(`${startDate} 00:00:00`);
    }
    
    if (endDate) {
      query += ' AND o.created_at <= ?';
      params.push(`${endDate} 23:59:59`);
    }
    
    const countQuery = query.replace('SELECT o.*, u.username as user, u.email', 'SELECT COUNT(*) as total');
    const [countRows] = await db.query(countQuery, params);
    const total = countRows[0].total;
    
    query += ' ORDER BY o.created_at DESC LIMIT ? OFFSET ?';
    params.push(Number(limit), Number(offset));
    
    const [rows] = await db.query(query, params);
    
    res.json({
      items: rows,
      total,
      page: Number(page),
      limit: Number(limit)
    });
  } catch (error) {
    console.error('获取订单列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取订单详情
router.get('/orders/:id', authenticate, isAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    
    // 获取订单基本信息
    const [orderRows] = await db.query(`
      SELECT o.*, u.username, u.email, u.created_at as register_time
      FROM orders o
      JOIN users u ON o.user_id = u.id
      WHERE o.id = ?
    `, [id]);
    
    if (orderRows.length === 0) {
      return res.status(404).json({ message: '订单不存在' });
    }
    
    const order = orderRows[0];
    
    // 获取订单商品
    const [itemRows] = await db.query(`
      SELECT oi.*, p.name, p.image
      FROM order_items oi
      JOIN products p ON oi.product_id = p.id
      WHERE oi.order_id = ?
    `, [id]);
    
    // 获取收货地址
    const [addressRows] = await db.query(`
      SELECT a.*
      FROM addresses a
      WHERE a.id = ?
    `, [order.shipping_address_id]);
    
    // 组装数据
    const result = {
      ...order,
      items: itemRows,
      user: {
        id: order.user_id,
        username: order.username,
        email: order.email,
        registerTime: order.register_time
      },
      shipping: addressRows.length > 0 ? {
        name: addressRows[0].name,
        phone: addressRows[0].phone,
        address: `${addressRows[0].province} ${addressRows[0].city} ${addressRows[0].address}`,
        postcode: addressRows[0].postcode
      } : null
    };
    
    // 删除冗余字段
    delete result.username;
    delete result.email;
    delete result.register_time;
    
    res.json(result);
  } catch (error) {
    console.error('获取订单详情错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新订单状态
router.put('/orders/:id/status', authenticate, isAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    await db.query(
      'UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?',
      [status, id]
    );
    
    res.json({ message: '订单状态更新成功' });
  } catch (error) {
    console.error('更新订单状态错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户列表
router.get('/users', authenticate, isAdmin, async (req, res) => {
  try {
    const { page = 1, limit = 10, username, email } = req.query;
    const offset = (page - 1) * limit;
    
    let query = `
      SELECT u.id, u.username, u.email, u.avatar,
             u.created_at as registerTime,
             COUNT(o.id) as orderCount
      FROM users u
      LEFT JOIN orders o ON u.id = o.user_id
      WHERE 1=1
    `;
    
    const params = [];
    
    if (username) {
      query += ' AND u.username LIKE ?';
      params.push(`%${username}%`);
    }
    
    if (email) {
      query += ' AND u.email LIKE ?';
      params.push(`%${email}%`);
    }
    
    query += ' GROUP BY u.id';
    
    // 计算总数
    const countQuery = `
      SELECT COUNT(*) as total 
      FROM users 
      WHERE 1=1
      ${username ? ' AND username LIKE ?' : ''}
      ${email ? ' AND email LIKE ?' : ''}
    `;
    
    const countParams = [];
    if (username) countParams.push(`%${username}%`);
    if (email) countParams.push(`%${email}%`);
    
    const [countRows] = await db.query(countQuery, countParams);
    const total = countRows[0].total;
    
    query += ' ORDER BY u.created_at DESC LIMIT ? OFFSET ?';
    params.push(Number(limit), Number(offset));
    
    const [rows] = await db.query(query, params);
    
    res.json({
      items: rows,
      total,
      page: Number(page),
      limit: Number(limit)
    });
  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户详情
router.get('/users/:id', authenticate, isAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    
    // 获取用户基本信息
    const [userRows] = await db.query(`
      SELECT u.id, u.username, u.email, u.avatar,
             u.created_at as registerTime, 
             NULL as last_login
      FROM users u
      WHERE u.id = ?
    `, [id]);
    
    if (userRows.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // 获取订单数量和总消费
    const [orderStats] = await db.query(`
      SELECT COUNT(id) as orderCount, IFNULL(SUM(total_amount), 0) as totalSpent
      FROM orders
      WHERE user_id = ? AND status != 'cancelled'
    `, [id]);
    
    // 获取最近订单
    const [recentOrders] = await db.query(`
      SELECT o.id, o.total_amount as amount, o.status, o.created_at as createTime
      FROM orders o
      WHERE o.user_id = ?
      ORDER BY o.created_at DESC
      LIMIT 5
    `, [id]);
    
    // 为每个订单获取商品
    for (let order of recentOrders) {
      const [items] = await db.query(`
        SELECT oi.product_id, p.name, oi.quantity
        FROM order_items oi
        JOIN products p ON oi.product_id = p.id
        WHERE oi.order_id = ?
      `, [order.id]);
      
      order.items = items;
    }
    
    // 获取收货地址数量
    const [addressCount] = await db.query(`
      SELECT COUNT(id) as count
      FROM addresses
      WHERE user_id = ?
    `, [id]);
    
    // 获取收货地址
    const [addresses] = await db.query(`
      SELECT id, name, phone, 
             CONCAT(province, ' ', city, ' ', address) as address, 
             postcode
      FROM addresses
      WHERE user_id = ?
    `, [id]);
    
    // 组装数据
    const result = {
      ...userRows[0],
      orderCount: orderStats[0].orderCount,
      totalSpent: orderStats[0].totalSpent,
      addressCount: addressCount[0].count,
      recentOrders,
      addresses
    };
    
    res.json(result);
  } catch (error) {
    console.error('获取用户详情错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户订单
router.get('/users/:id/orders', authenticate, isAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;
    
    // 获取总数
    const [countRows] = await db.query(
      'SELECT COUNT(*) as total FROM orders WHERE user_id = ?',
      [id]
    );
    const total = countRows[0].total;
    
    // 获取订单列表
    const [rows] = await db.query(`
      SELECT o.id, o.total_amount as amount, o.status, o.created_at as createTime,
             o.payment_method as paymentMethod
      FROM orders o
      WHERE o.user_id = ?
      ORDER BY o.created_at DESC
      LIMIT ? OFFSET ?
    `, [id, Number(limit), Number(offset)]);
    
    res.json({
      items: rows,
      total,
      page: Number(page),
      limit: Number(limit)
    });
  } catch (error) {
    console.error('获取用户订单错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取仪表盘数据
router.get('/dashboard', authenticate, isAdmin, async (req, res) => {
  try {
    // 获取总销售额
    const [salesData] = await db.query(`
      SELECT IFNULL(SUM(total_amount), 0) as totalSales
      FROM orders
      WHERE status NOT IN ('cancelled', 'pending')
    `);
    
    // 获取订单总数
    const [orderData] = await db.query(`
      SELECT COUNT(*) as totalOrders
      FROM orders
    `);
    
    // 获取用户总数
    const [userData] = await db.query(`
      SELECT COUNT(*) as totalUsers
      FROM users
    `);
    
    // 获取商品总数
    const [productData] = await db.query(`
      SELECT COUNT(*) as totalProducts
      FROM products
    `);
    
    // 获取热销商品
    const [hotProducts] = await db.query(`
      SELECT p.id, p.name, p.price, p.image, SUM(oi.quantity) as sales
      FROM products p
      JOIN order_items oi ON p.id = oi.product_id
      JOIN orders o ON oi.order_id = o.id
      WHERE o.status NOT IN ('cancelled', 'pending')
      GROUP BY p.id
      ORDER BY sales DESC
      LIMIT 5
    `);
    
    // 获取最新订单
    const [latestOrders] = await db.query(`
      SELECT o.id, o.total_amount as amount, o.status, o.created_at as time,
             u.username as user
      FROM orders o
      JOIN users u ON o.user_id = u.id
      ORDER BY o.created_at DESC
      LIMIT 5
    `);
    
    // 返回仪表盘数据
    res.json({
      statistics: {
        totalSales: salesData[0].totalSales,
        totalOrders: orderData[0].totalOrders,
        totalUsers: userData[0].totalUsers,
        totalProducts: productData[0].totalProducts
      },
      hotProducts,
      latestOrders
    });
  } catch (error) {
    console.error('获取仪表盘数据错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

export default router; 